//
//  CZNetworkTool.swift
//  SinaBlog
//
//  Created by 李超 on 16/3/21.
//  Copyright © 2016年 lichao. All rights reserved.
//

import UIKit
import AFNetworking

enum CZNetworkToolError: Int {
    
    case AccessTokenEmpty = -1
    case UidEmpty = -2
    case StatusLoading = -3
    //枚举值可以有属性
    var errorMessage:String{
        switch self{
        case .AccessTokenEmpty:return "access_token为空"
        case .UidEmpty:return "uid为空"
        case .StatusLoading:return "微博正在加载数据，请稍等···"
        }

    }
    //返会对应的错误信息
    func error() -> NSError{
       return NSError(domain: "cn.itcast.net", code: self.rawValue, userInfo: ["errorMessage":errorMessage])
    }
    
}

class CZNetworkTool: NSObject {
    
    //做成一个单例，供全局使用
    static let shareInstance:CZNetworkTool = CZNetworkTool()
    
    var netManager:AFHTTPSessionManager

    //将唯一的构造方法私有化杜绝通过构造方法产生新对象
    private override init() {
        
        let baseURL = NSURL(string: "https://api.weibo.com/")
        netManager = AFHTTPSessionManager(baseURL: baseURL!)
        netManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        super.init()
        
    }
    //封装AFHTTPSessionManager的get方法以便于日后维护
    func requestGet(URLString: String,var parameters: [String : AnyObject]?,completionHandler:(result:[String : AnyObject]?,error:NSError?)->()){
        //进行判断access_token
        guard let access_token = CZUserAccountTool.shareInstance.userAccount?.access_token else{
            
            completionHandler(result: nil, error: CZNetworkToolError.AccessTokenEmpty.error())
            return
        }
        //判断外面传入的参数是否为空，如果为空，则需要自己赋值，避免崩溃
        if parameters == nil{
            parameters = [String : AnyObject]()
        }
        //自己拼接上acce——token
        parameters!["access_token"] = access_token
        //第三方请求方法
        netManager.GET(URLString, parameters: parameters, progress: nil, success: { (_, results) -> Void in
            
            completionHandler(result:results as? [String : AnyObject], error: nil)
            
            }) { (_, errors) -> Void in
                
            completionHandler(result: nil, error: errors)
                
        }
    
    }
    //封装AFHTTPSessionManager的post方法以便于日后维护
    func requestPost(URLString: String, parameters: [String : AnyObject]?,completionHandler:(result:[String : AnyObject]?,error:NSError?)->()){
        //日后如需维护，只需要更改这一段代码即可
        netManager.POST(URLString, parameters: parameters, progress: nil, success: { (_, results) -> Void in
            //执行回调
            completionHandler(result:results as? [String : AnyObject], error: nil)
            
            }) { (_, error) -> Void in
            //执行回调
             completionHandler(result: nil, error: error)
        }
        
        
    }
    
}












